package com.fh.module_main.ui.fragment

import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.view.View.*
import android.widget.*
import androidx.core.content.ContextCompat.getColor
import androidx.lifecycle.Observer
import androidx.navigation.NavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.fh.lib_base.base.BaseFragment
import com.fh.lib_base.config.AppConstants
import com.fh.lib_base.data.bean.BannerBean
import com.fh.lib_base.ext.nav
import com.fh.lib_base.ext.navigateAction
import com.fh.lib_base.util.AppUtils
import com.fh.lib_base.util.DateUtil
import com.fh.lib_base.util.SpHelper
import com.fh.module_main.BR
import com.fh.module_main.R
import com.fh.module_main.adapter.*
import com.fh.module_main.databinding.MainFragmentSearchBinding
import com.fh.module_main.databinding.MainSearchCalendarDialogBinding
import com.fh.module_main.databinding.MainSearchFragmentCitylistDialogBinding
import com.fh.module_main.ext.jumpByLogin
import com.fh.module_main.view.CustomCalendarListView
import com.fh.module_main.view.FastIndexView
import com.fh.module_main.viewmodel.SearchFragmentViewModel
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.gyf.immersionbar.ImmersionBar
import com.zhpan.bannerview.BannerViewPager
import com.zhpan.bannerview.utils.BannerUtils
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

@Route(path = AppConstants.Router.Main.MAIN_SEARCH_FRAGMENT)
class SearchFragment: BaseFragment<MainFragmentSearchBinding, SearchFragmentViewModel>() {

    var currentTab: Int = 0
    private lateinit var mViewPager: BannerViewPager<BannerBean, HomeBannerViewHolder>
    private lateinit var quanriRL: RelativeLayout
    private lateinit var shizuRL: RelativeLayout
    private lateinit var minsuRL: RelativeLayout
    private lateinit var qianriTV: TextView
    private lateinit var shizuTV: TextView
    private lateinit var minsuTV: TextView
    private lateinit var zhiTV: TextView //至 字
    private lateinit var leaveTimeLL: LinearLayout //离店布局
    private lateinit var neightCountTV: TextView //共2晚
    private lateinit var peopleCountTV: TextView //人数
    private lateinit var keywordsET: EditText //关键词
    private lateinit var addressTV: TextView //地址
    //热门城市
    private lateinit var hotListAdapter: HotListFlowRecyclerAdapter
    //所有城市
    private lateinit var allCityListAdapter: CityListAdapter
    //城市搜索结果列表
    private lateinit var citySearchResultListAdapter: CitySearchResultListAdapter
    private lateinit var linearLayoutManager: LinearLayoutManager
    private var defaultStart: String = "" //默认入住日期
    private var defaultEnd: String = "" //默认离店日期

    override fun initContentView(): Int {
        return R.layout.main_fragment_search
    }

    override fun initVariableId(): Int {
        return BR.viewModel
    }
    override fun onSupportVisible() {
        ImmersionBar.with(this).statusBarDarkFont(false).init()
    }

    override fun useBaseLayout(): Boolean {
        return false
    }
    override fun initData() {
        initView()
        viewModel.getSearchBannerData()
        //获取热门城市和所有城市数据
        viewModel.getHotCityListData()
        viewModel.getAllCityListData()
        setupViewPager()
    }
    private fun initView(){
        //开启定位
        viewModel.getCurrentLocation()
        quanriRL = binding.searchQuanrifangRl
        shizuRL = binding.searchShizufangRl
        minsuRL = binding.searchMinsuRl
        qianriTV = binding.searchQuanrifangTv
        shizuTV = binding.searchShizufangTv
        minsuTV = binding.searchMinsuTv

        zhiTV = binding.mainZhi
        leaveTimeLL = binding.mainLeaveTime
        neightCountTV = binding.mainNeightCount
        peopleCountTV = binding.mainPeopleCount
        keywordsET = binding.mainHotelKeyword
        addressTV = binding.mainAddress
        //初始化日期
        var format = SimpleDateFormat("yyyy-MM-dd")
        defaultStart = format.format(Date())

        var calendar = Calendar.getInstance()
        calendar.time = Date()
        calendar.add(Calendar.DAY_OF_MONTH,1)
        defaultEnd = format.format(calendar.time)
        binding.mainSearchStartdate.text = defaultStart.substring(5,10)
        binding.mainSearchEnddate.text = defaultEnd.substring(5,10)

        //点击全日房
        quanriRL.apply {
            setOnClickListener {
                if(currentTab != 0){
                    currentTab = 0
                    quanriRL.setBackgroundResource(R.mipmap.search_select_left)
                    shizuRL.setBackground(null)
                    minsuRL.setBackground(null)
                    qianriTV.setTextColor(getColor(context,R.color.black_font))
                    shizuTV.setTextColor(getColor(context,R.color.white))
                    minsuTV.setTextColor(getColor(context,R.color.white))

                    zhiTV.visibility = VISIBLE
                    leaveTimeLL.visibility = VISIBLE
                    neightCountTV.visibility = VISIBLE
                    peopleCountTV.visibility = INVISIBLE
                    keywordsET.hint = resources.getString(R.string.hotel_keyword)
                    //每次切换tab 日期都是今天
                    calendar.time = Date()
                    calendar.add(Calendar.DAY_OF_MONTH,1)
                    defaultStart = format.format(Date())
                    defaultEnd = format.format(calendar.time)
                    binding.mainSearchStartdate.text = defaultStart.substring(5,10)
                    binding.mainSearchEnddate.text = defaultEnd.substring(5,10)
                }
            }
        }
        //点击时租房
        shizuRL.apply {
            setOnClickListener {
                if(currentTab != 1){
                    currentTab = 1
                    quanriRL.setBackground(null)
                    shizuRL.setBackgroundResource(R.mipmap.search_select_middle)
                    minsuRL.setBackground(null)
                    qianriTV.setTextColor(getColor(context,R.color.white))
                    shizuTV.setTextColor(getColor(context,R.color.black_font))
                    minsuTV.setTextColor(getColor(context,R.color.white))
                    keywordsET.hint = resources.getString(R.string.hotel_keyword)

                    zhiTV.visibility = INVISIBLE
                    leaveTimeLL.visibility = INVISIBLE
                    neightCountTV.visibility = INVISIBLE
                    peopleCountTV.visibility = INVISIBLE
                    //每次切换tab 日期都是今天
                    calendar.time = Date()
                    defaultStart = format.format(Date())
                    calendar.add(Calendar.DAY_OF_MONTH,1)
                    defaultEnd = format.format(calendar.time)
                    binding.mainSearchStartdate.text = defaultStart.substring(5,10)
                    binding.mainSearchEnddate.text = defaultEnd.substring(5,10)
                }
            }
        }

        //点击民宿
        minsuRL.apply {
            setOnClickListener {
                if(currentTab != 2){
                    currentTab = 2
                    quanriRL.setBackground(null)
                    shizuRL.setBackground(null)
                    minsuRL.setBackgroundResource(R.mipmap.search_select_right)
                    qianriTV.setTextColor(getColor(context,R.color.white))
                    shizuTV.setTextColor(getColor(context,R.color.white))
                    minsuTV.setTextColor(getColor(context,R.color.black_font))
                    keywordsET.hint = resources.getString(R.string.minsu_keyword)

                    zhiTV.visibility = VISIBLE
                    leaveTimeLL.visibility = VISIBLE
                    neightCountTV.visibility = VISIBLE
                    peopleCountTV.visibility = VISIBLE
                    //每次切换tab 日期都是今天
                    calendar.time = Date()
                    calendar.add(Calendar.DAY_OF_MONTH,1)
                    defaultStart = format.format(Date())
                    defaultEnd = format.format(calendar.time)
                    binding.mainSearchStartdate.text = defaultStart.substring(5,10)
                    binding.mainSearchEnddate.text = defaultEnd.substring(5,10)
                }
            }
        }
        //重新定位
        binding.mainCurrentPosition.apply {
            setOnClickListener {
                viewModel.getCurrentLocation()
            }
        }
        //点击入住时间
        binding.mainLeaveTime.apply {  }
        binding.mainPushTime.apply {
            setOnClickListener {
                SpHelper.encode(AppConstants.SpKey.QUANRI_START_DATE,defaultStart)
                SpHelper.encode(AppConstants.SpKey.QUANRI_END_DATE,defaultEnd)
                val calendarDialog = BottomSheetDialog(context)
                val viewBinding = MainSearchCalendarDialogBinding.inflate(layoutInflater)
                viewBinding.calendarList.setOnDateSelected(object: CustomCalendarListView.OnDateSelected{
                    override fun selected(startDate: String, endDate: String) {
                        var startWeek = DateUtil.getWeekByDate(startDate)
                        var endWeek = DateUtil.getWeekByDate(endDate)
                        calendarDialog.cancel()
                        defaultStart = startDate
                        defaultEnd = endDate
                        binding.mainSearchStartweek.text = startWeek
                        binding.mainSearchEndweek.text = endWeek
                        binding.mainSearchStartdate.text = startDate.substring(5,10)
                        binding.mainSearchEnddate.text = endDate.substring(5,10)

                    }
                },currentTab)
                calendarDialog.setCancelable(true)
                calendarDialog.setContentView(viewBinding.root)
                calendarDialog.show()
            }
        }
        //底部弹出城市列表,dialog的布局文件中直接用dataBinding值为啥是空
        binding.mainAddress.apply {
            val viewBinding = MainSearchFragmentCitylistDialogBinding.inflate(layoutInflater)
            val dialog = BottomSheetDialog(context)
            //热门城市
            hotListAdapter = HotListFlowRecyclerAdapter(viewModel.hotCityData.value)

            viewBinding.citylistDialogHotcityList.apply {
                val foxLayoutManager: FlexboxLayoutManager by lazy {
                    FlexboxLayoutManager(context).apply {
                        //方向 主轴为水平方向，起点在左端
                        flexDirection = FlexDirection.ROW
                        //左对齐
                        justifyContent = JustifyContent.FLEX_START
                    }
                }
                layoutManager = foxLayoutManager
                setHasFixedSize(true)
                isNestedScrollingEnabled = false
                adapter = hotListAdapter
                hotListAdapter.setOnItemClickListener(object: HotListFlowRecyclerAdapter.ItemClickListener{
                    override fun onClick(pos: Int) {
                        dialog.cancel()
                        addressTV.text = hotListAdapter.data[pos].name
                    }
                })
            }
            //所有城市列表
            viewBinding.citylistDialogAllcityList.apply {
                linearLayoutManager = LinearLayoutManager(context)
                layoutManager = linearLayoutManager
                addItemDecoration(CustomItemDecoration(context,object: CustomItemDecoration.TitleDecorationCallback{
                    override fun getGroupId(position: Int): String {
                        //这个是用来比较是否是同一组数据的
                        return viewModel.allCityListData.value!!.get(position).sortId
                    }
                    override fun getGroupName(position: Int): String {
                        var cityInfoModel = viewModel.allCityListData.value!!.get(position)
//                            //拼音都是小写的
                        return cityInfoModel.sortId.uppercase()
                    }
                }))
                //所有城市
                if(viewModel.allCityListData.value == null){
                    viewModel.allCityListData.value = ArrayList()
                }
                if(viewModel.allCityListData.value == null){
                    viewModel.allCityListData.value = ArrayList()
                }
                allCityListAdapter = CityListAdapter(context, viewModel.allCityListData.value!!)
                setAdapter(allCityListAdapter)
                allCityListAdapter.setOnItemClickListener(object: CityListAdapter.ItemClickListener {
                    override fun onClick(pos: Int) {
                        dialog.cancel()
                        addressTV.text = allCityListAdapter.data[pos].name
                    }
                })
                //滑动监听
                addOnScrollListener(object: RecyclerView.OnScrollListener() {
                    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                        super.onScrolled(recyclerView, dx, dy)
                        var manager = recyclerView.getLayoutManager()
                        var position = (manager as LinearLayoutManager).findFirstVisibleItemPosition()
                        if(viewModel.allCityListData.value!!.size > 0){
                            viewBinding.fastIndexView.setLetter(viewModel.allCityListData.value!!.get(position).sortId)
                        }
                    }
                })
            }
            initListener(viewBinding.fastIndexView,linearLayoutManager)
            //搜索结果列表
            viewBinding.citylistDialogSearchRecyclerview.apply {
                layoutManager = LinearLayoutManager(context)
                //搜索结果
                viewModel.citySearchResultListData.value = ArrayList()
                citySearchResultListAdapter = CitySearchResultListAdapter(context,viewModel.citySearchResultListData.value!!)
                setAdapter(citySearchResultListAdapter)
                citySearchResultListAdapter.setOnItemClickListener(object: CitySearchResultListAdapter.ItemClickListener{
                    override fun onClick(pos: Int) {
                        dialog.cancel()
                        addressTV.text = citySearchResultListAdapter.data[pos].name
                    }
                })
            }
            //搜索框获取焦点
            viewBinding.citylistDialogEdittext.setOnFocusChangeListener(object: View.OnFocusChangeListener{
                override fun onFocusChange(v: View?, hasFocus: Boolean) {
                    if(hasFocus){
                        viewBinding.citylistDialogSearchCancle.visibility = VISIBLE
                        viewBinding.citylistDialogContentLl.visibility = GONE
                        viewBinding.citylistDialogSearchResult.visibility = VISIBLE
                    }else{
                        viewBinding.citylistDialogSearchCancle.visibility = INVISIBLE
                        viewBinding.citylistDialogContentLl.visibility = VISIBLE
                        viewBinding.citylistDialogSearchResult.visibility = GONE
                        viewBinding.citylistDialogEdittext.clearFocus()
                    }
                }
            })
            viewBinding.citylistDialogEdittext.addTextChangedListener(object: TextWatcher{
                override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
                }
                override fun onTextChanged(s: CharSequence,start: Int,before: Int,count: Int) {
                }
                override fun afterTextChanged(s: Editable) {
                    //发起搜索
                    if(!TextUtils.isEmpty(s.toString())){
                        viewModel.getCitySearchResultListData(s.toString())
                    }
                }
            })
            viewBinding.citylistDialogSearchCancle.setOnClickListener {
                viewBinding.citylistDialogSearchCancle.visibility = INVISIBLE
                viewBinding.citylistDialogContentLl.visibility = VISIBLE
                viewBinding.citylistDialogSearchResult.visibility = GONE
                viewBinding.citylistDialogEdittext.clearFocus()
                //关闭软键盘
                AppUtils.closeKeyBroad(context,viewBinding.citylistDialogEdittext)
            }
            viewBinding.citylistDialogCancle.setOnClickListener {
                dialog.cancel()
            }
            //点击事件 弹窗显示与关闭
            setOnClickListener {
                viewBinding.citylistDialogCurrentAddress.text = "当前位置：${viewModel.locationLiveData.value!!.city}" +
                        "${viewModel.locationLiveData.value!!.district}${viewModel.locationLiveData.value!!.street}"
                viewBinding.citylistDialogCurrentCity.text = "当前城市：${viewModel.locationLiveData.value!!.city}"
                dialog.setCancelable(false)
                dialog.setContentView(viewBinding.root)
                dialog.show()
            }
        }
        //点击查询按钮，跳转酒店列表Fragment
        binding.mainQuery.apply {
            setOnClickListener {
                nav().jumpByLogin {
                    it.navigateAction(R.id.main_action_main_searchfragment_to_main_hotellistfragment2)
                }
            }
        }
    }
    //创建LiveData观察者 Fragment执行onViewCreated后触发
    override fun initViewObservable() {
        //run函数的匿名函数持有this，最后一行为返回值
        viewModel.run {
           bannerData.observe(viewLifecycleOwner, Observer {
              mViewPager.refreshData(it)
           })
           locationLiveData.observe(viewLifecycleOwner, Observer {
               addressTV.text = "${it.city}${it.district}${it.street}"
           })
           hotCityData.observe(viewLifecycleOwner, Observer {
               if(it != null && it.size > 0){
                   hotListAdapter.data.clear()
                   hotListAdapter.data.addAll(it)
                   hotListAdapter.notifyDataSetChanged()
               }
           })
           allCityListData.observe(viewLifecycleOwner, Observer {
               if(it != null && it.size > 0){
                   allCityListAdapter.data.clear()
                   allCityListAdapter.data.addAll(it)
                   allCityListAdapter.notifyDataSetChanged()
               }
           })
           citySearchResultListData.observe(viewLifecycleOwner, Observer {
               if(it != null && it.size > 0){
                   citySearchResultListAdapter.data.clear()
                   citySearchResultListAdapter.data.addAll(it)
                   citySearchResultListAdapter.notifyDataSetChanged()
               }
           })
        }
    }
    //设置BannerViewPager适配器，
    private fun setupViewPager() {
        mViewPager = binding.mainSearchBannerView as BannerViewPager<BannerBean, HomeBannerViewHolder>
        mViewPager.apply {
            adapter = HomeBannerAdapter()
            setAutoPlay(true)
            registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    BannerUtils.log("position:$position")
                }
            })
        }.create()
    }
    fun initListener(fastIndexView: FastIndexView,layoutManager:LinearLayoutManager) {
        fastIndexView.setListener(object: FastIndexView.OnLetterUpdateListener {
            override fun onLetterUpdate(letter: String?) {
                moveToLetterPosition(letter!!,layoutManager);
            }
        });
    }
    //滚动recyclerview
    fun moveToLetterPosition(letter: String,layoutManager:LinearLayoutManager) {
        //这里主要是为了跳转到最顶端
        if ("#".equals(letter)) {
            layoutManager.scrollToPositionWithOffset(0, 0);
        }
        for (i in viewModel.allCityListData.value!!) {
            if (i.sortId.uppercase().equals(letter)) {
                layoutManager.scrollToPositionWithOffset(viewModel.allCityListData.value!!.indexOf(i), 0);
                return;
            }
        }
    }
}